#define _CRT_SECURE_NO_WARNINGS 1
#include"SLNode.h"

SL* SLCreatNode(SLNDataType x)
{
	SL* node = (SL*)malloc(sizeof(SL));
	if (node == NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	node->data = x;
	node->next = NULL;
	return node;
}
void SLPrint(SL* sl)
{
	assert(sl);
	SL* pcur = sl;
	while (pcur)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
}

void SLPushFront(SL* phead, SLNDataType x)
{

	SL* newnode = SLCreatNode(x);
	if (phead == NULL)
	{
		phead = newnode;
	}
	SL* pcur = phead;
	newnode->next = pcur;
	pcur = newnode;
}
void SLPushBack(SL** phead, SLNDataType x)
{
	SL* newnode = SLCreatNode(x);
	if (phead == NULL)
	{
		phead = newnode;
	}
	SL* ptail = phead;
	ptail->next = newnode;
	ptail = newnode;
}
void SLPopFront(SL* phead)
{
	assert(phead);
	SL* next = phead->next;
	free(phead);
	phead = next;
}
void SLPopBack(SL* phead)
{
	assert(phead);
	SL* pcur = phead;
	SL* pre = NULL;
	while (pcur->next)
	{
		pre = pcur;
		pcur = pcur->next;
	}
	if (pre != NULL)
	{
		pre->next = NULL;
	}
	free(pcur);
	pcur = NULL;
}
SL* SLFind(SL* phead, SLNDataType x)
{
	assert(phead);
	SL* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
void SLInset(SL* phead, SL* pos, SLNDataType e)
{
	assert(phead);
	SL* newnode = SLCreatNode(e);
	if (phead == pos)
	{
		newnode->next = phead;
		phead = newnode;
	}
	else
	{
		SL* pcur = phead;
		while (pcur->next)
		{
			if (pcur->next == pos)
			{
				newnode->next = pos;
				pcur->next = newnode;
				break;
			}
			pcur = pcur->next;
		}
	}
}
void SLPop(SL* phead, SL* pos)
{
	assert(phead);
	if (phead == pos)
	{
		free(phead);
		phead = NULL;
		pos = NULL;
	}
	else
	{
		SL* pcur = phead;
		while (pcur->next)
		{
			if (pcur->next == pos)
			{
				pcur->next = pcur->next->next;
				free(pos);
				pos = NULL;
				break;
			}
			pcur = pcur->next;
		}
	}	
}
void SLDestroy(SL** phead)
{
	assert(phead && *phead);
	SL* pcur = *phead;
	while (pcur)
	{
		SL* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	pcur = NULL;
	*phead = NULL;
}